﻿import com.gamepackage.events.Call;
import com.gamepackage.events.Executable;

class com.gamepackage.events.EventDeflector
{
	static function initialize( o: Object ): Void
	{
		var e: EventDeflector = new EventDeflector;

		o.addDeflection 	= e.addDeflection;
		o.removeDeflection 	= e.removeDeflection;
		o.deflectEvent 		= e.deflectEvent;
		o.deflections		= new Object();
	}

	private var deflections: Object;

	function addDeflection( msg: String, exe: Executable ): Void
	{
		var queueName = "__q_" + msg;
		if ( deflections[ queueName ] == undefined )
		{
			deflections[ queueName ] = new Array();
		}
		deflections[ queueName ].push( exe );
	}

	function removeDeflection( msg: String, exe: Executable ): Boolean
	{
		var exes: Array = deflections[ "__q_" + msg ];
		var e: Number = exes.length;
		while( --e > -1 )
		{
			if ( exes[e] == exe )
			{
				exes.splice( e , 1 );
				if ( exes.length == 0 ) delete deflections[ "__q_" + msg ];
				return true;
			}
		}
		return false;
	}

	private function deflectEvent( msg: String ): Void
	{
		var args: Array = arguments.slice( 1 );
		
		var exes: Array = deflections[ "__q_" + msg ];
		var e: Number = exes.length;

		if ( args.length )
		{
			var exe: Executable;

			while( --e > -1 )
			{
				exe.execute.apply( exe = exes[e] , args );
			}
		}
		else
		{
			while( --e > -1 )
			{
				exes[e].execute();
			}
		}
	}
}